#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
演示启动脚本
用于演示双向TLS通信系统
"""

import subprocess
import sys
import time
import threading
from pathlib import Path

def check_certificates():
    """检查证书是否存在"""
    cert_files = [
        'certs/ca-cert.pem',
        'certs/server-cert.pem',
        'certs/server-key.pem',
        'certs/client-cert.pem',
        'certs/client-key.pem'
    ]
    
    missing_files = []
    for cert_file in cert_files:
        if not Path(cert_file).exists():
            missing_files.append(cert_file)
    
    return missing_files

def generate_certificates():
    """生成证书"""
    print("正在生成证书...")
    try:
        result = subprocess.run([sys.executable, 'generate_certs.py'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✓ 证书生成成功")
            return True
        else:
            print(f"✗ 证书生成失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"✗ 证书生成失败: {e}")
        return False

def run_server():
    """运行服务器"""
    print("启动ESP32服务器...")
    try:
        subprocess.run([sys.executable, 'esp32_server.py'])
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"服务器运行错误: {e}")

def run_client():
    """运行客户端"""
    print("启动客户端...")
    time.sleep(2)  # 等待服务器启动
    try:
        subprocess.run([sys.executable, 'client.py'])
    except KeyboardInterrupt:
        print("\n客户端已停止")
    except Exception as e:
        print(f"客户端运行错误: {e}")

def main():
    print("=== 双向TLS通信演示系统 ===")
    print()
    
    # 检查证书
    missing_certs = check_certificates()
    if missing_certs:
        print("缺少证书文件:")
        for cert in missing_certs:
            print(f"  - {cert}")
        print()
        
        response = input("是否自动生成证书? (y/n): ").strip().lower()
        if response in ['y', 'yes', '是']:
            if not generate_certificates():
                print("证书生成失败，程序退出")
                return
        else:
            print("请先生成证书后再运行演示")
            return
    else:
        print("✓ 证书文件检查通过")
    
    print()
    print("选择运行模式:")
    print("1. 同时启动服务器和客户端 (推荐)")
    print("2. 仅启动服务器")
    print("3. 仅启动客户端")
    print()
    
    choice = input("请选择 (1-3): ").strip()
    
    if choice == '1':
        print("\n启动服务器和客户端...")
        print("注意: 服务器将在后台运行，客户端在前台运行")
        print("按 Ctrl+C 可以停止程序")
        print()
        
        # 在新线程中启动服务器
        server_thread = threading.Thread(target=run_server, daemon=True)
        server_thread.start()
        
        # 在主线程中运行客户端
        run_client()
        
    elif choice == '2':
        print("\n仅启动服务器...")
        print("按 Ctrl+C 可以停止服务器")
        print()
        run_server()
        
    elif choice == '3':
        print("\n仅启动客户端...")
        print("请确保服务器已在运行")
        print()
        run_client()
        
    else:
        print("无效选择")
        return
    
    print("\n演示结束")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n程序被中断")
    except Exception as e:
        print(f"程序运行错误: {e}")